import express from 'express';
import { createServer } from 'node:http';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
// import { Server } from 'socket.io';
import { io } from 'socket.io-client';

const app = express();
const server = createServer(app);
const port = 3003;
// const io = new Server(server);

const AUTH_TOKEN = 'e97b51bb-7ed4-4d39-b826-1a2c2f0d9e76';
const PLAYER_TOKENS = ['4ab6d84a-fe23-4f14-9d7c-e49a5435e8c3'];

const __dirname = dirname(fileURLToPath(import.meta.url));

// app.get('/', (req, res) => {
//   // console.log(req);
//   res.sendFile(join(__dirname, 'index.html'));
// });

app.use('/node_modules', express.static('node_modules'));

class Connector {
  AUTH_TOKEN = '';
  WSS_URL = 'wss://tt2-public.gamehivegames.com';
  REST_URL = 'https://tt2-public.gamehivegames.com';
  constructor(authToken) {
    this.AUTH_TOKEN = authToken;
  }

  raidRestConnect = () => {
    fetch(`${this.REST_URL}/raid/subscribe`, {
      method: 'post',
      headers: {
        'API-Authenticate': this.AUTH_TOKEN,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ player_tokens: PLAYER_TOKENS }),
    })
      .then(res => res.json())
      .then(res => {
        console.log('====');
        console.log(res);
      })
      .catch(e => {
        console.log('====');
        console.log(e);
      });
  };

  playerRestConnect = () => {
    fetch(`${this.REST_URL}/player/data`, {
      method: 'post',
      headers: {
        'API-Authenticate': this.AUTH_TOKEN,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ player_token: PLAYER_TOKENS[0], properties: ['titan_cards', 'cards'] }),
    })
      .then(res => res.json())
      .then(res => {
        console.log('====');
        console.log(res);
      })
      .catch(e => {
        console.log('====');
        console.log(e);
      });
  };

  connect = async ({ timeout = 5000 } = {}) => {
    // 创建 Socket.IO 客户端实例
    const commonOptions = {
      transports: ['websocket'],
      extraHeaders: { 'API-Authenticate': this.AUTH_TOKEN },
      path: '/api', // 对应 Python 中的 socketio_path
      autoConnect: false, // 不自动连接，等待手动调用 connect()
      reconnection: false, // 禁用自动重连，与 Python 代码行为一致
      timeout,
    };
    const raidIO = io(`${this.WSS_URL}/raid`, commonOptions);
    const playerIO = io(`${this.WSS_URL}/player`, commonOptions);

    // 等待连接成功的 Promise 封装
    const connectPromise = new Promise((resolve, reject) => {
      // 默认事件
      raidIO.on('connect', () => {
        this.raidRestConnect();
        resolve();
      });
      raidIO.on('error', error => {
        reject(new Error(`raidIO连接失败: ${error.message}`));
      });
      // TT2事件
      raidIO.on('connected', () => {
        console.log('!!!!connected!!!!');
      });
      raidIO.on('start', data => {
        console.log('!!!!start!!!!');
        console.log(data);
      });
      raidIO.on('sub_start', data => {
        console.log('!!!!sub_start!!!!');
        console.log(data);
      });
      raidIO.on('end', data => {
        console.log('!!!!end!!!!');
        console.log(data);
      });

      playerIO.on('connect', this.playerRestConnect);
      playerIO.on('error', error => {
        reject(new Error(`playerIO连接失败: ${error.message}`));
      });

      // 开始连接
      raidIO.connect();
      playerIO.connect();
    });

    // 等待连接完成
    await connectPromise;

    // 保持连接
    return new Promise(resolve => {
      // 当所有命名空间都断开时才会结束

      raidIO.on('disconnect', () => {
        resolve();
      });
    });
  };
}

const excute = async () => {
  const connector = new Connector(AUTH_TOKEN);
  console.log('准备连接');
  await connector.connect();
  console.log('断开连接');
};

excute();
